﻿// owner 蒋家伟

#pragma once

// qt
#include <QObject>
#include <QByteArray>
#include <QSerialPort>

// jsdk
#include "ISerialPortEventHandler.h"
#include "WeakPtr.h"

namespace jsdk
{
    class SerialPortWorker : public QObject
    {
        Q_OBJECT
    public:
        ~SerialPortWorker() {};

        static OwnerPtr<SerialPortWorker> create(ISerialPortEventHandler * pSerialPortEventHandler);

        /// \ 当前是否work是否再工作，或者说在线
        bool isOnLine() const;

#pragma region 跨线程与串口的通讯信号与槽
    public slots:
        // 当前线程接受的槽，由ISocket跨线程触发
        void onConnect(
            QString port,
            int baudRate,
            short dataBits,
            short stopBits,
            short parity,
            short flowControl
            );

        void onSend(QByteArray msg, qint64 length);

#pragma region 跨线程与串口的通讯信号与槽

#pragma region 当前串口使用的信号与槽
    private slots:
        // socket触发的槽函数
        void onReadyRead();
        void onError(QSerialPort::SerialPortError serialPortError) const;

#pragma region 当前串口使用的信号与槽

    private:
        bool init() const;
        SerialPortWorker() {};
        struct SerialPortDeleter
        {
            void operator()(QSerialPort*);
        };

    private:
        OwnerPtr<QSerialPort, SerialPortDeleter> m_opSerialPort;
        WeakPtr<ISerialPortEventHandler> m_wpSerialPortHandler;
    };
}